/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-10 11:00:00
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-14 14:43:38
 * @FilePath: \gogamewebserver\goGameWebServer\internal\model\entity\avatarModel.go
 * @Description: Avatar 实体模型
 */
package entity

import (
	"goGameWebServer/internal/common/logger"
	"goGameWebServer/internal/common/utils"
	"goGameWebServer/internal/defines/cerror"
	"goGameWebServer/internal/defines/dataType"
	"goGameWebServer/internal/interfaces"
	"goGameWebServer/internal/manager/databasemanager"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/util/gmeta"
)

type AvatarModelData struct {
	gmeta.Meta `orm:"table: avatar"`
	Id         dataType.TypeDataBaseId `orm:"id"`         // 角色ID
	Name       string                  `orm:"name" `      // 角色名称
	Data       string                  `orm:"data" `      // 角色数据
	UseServer  int                     `orm:"useServer"`  // 强制使用服务器数据标记
	CreateTime string                  `orm:"createTime"` // 创建时间
	LastTime   string                  `orm:"lastTime"`   // 登出时间
}

func (avatarModelData *AvatarModelData) Reset() {
	avatarModelData.Id = 0
	avatarModelData.Name = ""
	avatarModelData.Data = ""
	avatarModelData.UseServer = 0
	avatarModelData.CreateTime = ""
	avatarModelData.LastTime = ""
}

type AvatarModel struct {
	EntityModel
}

func (avatarModel *AvatarModel) LoadEntityDataFromDB(records interface{}) error {
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return err
	}
	if entityData, ok := avatarModel.EntityData.(*AvatarModelData); ok {
		// 根据 id 加载，如不存在则创建
		one, err := base.GetDb().Model(avatarModel.Template).Where("id", entityData.Id).One()
		if err != nil {
			return err
		}
		if one == nil {
			return avatarModel.Create()
		}
		_ = one.Struct(avatarModel.EntityData)
		avatarModel.SetEntityDBID(entityData.Id)
		return nil
	}
	return gerror.NewCodef(gcode.New(cerror.ERROR_ENTITY_PROPERTY_INVALID, "", nil),
		"avatar module model data is invalid")
}

func (avatarModel *AvatarModel) Create() error {
	if entityData, ok := avatarModel.EntityData.(*AvatarModelData); ok {
		entityData.CreateTime = utils.GetNowTimeFormat()
		entityData.LastTime = utils.GetNowTimeFormat()
		err := avatarModel.CreateDataToDB()
		entityData.Id = avatarModel.EntityDBID
		if err != nil {
			return err
		}
		logger.LoggerIns().Debug("create avatar base success")
		return nil
	}
	return gerror.NewCodef(gcode.New(cerror.ERROR_ENTITY_PROPERTY_INVALID, "", nil),
		"avatar module model create fail, data is invalid")
}

func NewAvatarModel(name string) interfaces.IEntityModel {
	m := &AvatarModel{
		EntityModel: NewEntityModel(name),
	}
	m.SetEntityData(&AvatarModelData{
		Id:         0,
		Name:       "",
		Data:       "",
		UseServer:  0,
		CreateTime: "",
		LastTime:   "",
	})
	m.SetTemplate(m.EntityData)
	return m
}
